package nsn.message.aggregator.wizzards;


import nsn.message.aggregator.model.IMessageAggregator;
import nsn.message.aggregator.model.ISourceType;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;

/**
 * 
 * 
 * @author Lukasz Nowak
 * @since 11-03-2011
 * 
 */
public class SelectSourceTypePage extends WizardPage {

	private static final String PAGE_NAME = "Select Source type.";
	private static final String TITLE = "Source Type";
	private static final ImageDescriptor TITLE_IMAGE = null;

	private final IMessageAggregator _model;
	private Class<?> _sourceTypeClass;

	/**
	 * 
	 * 
	 * @param model
	 */
	public SelectSourceTypePage(final IMessageAggregator model) {
		super(PAGE_NAME, TITLE, TITLE_IMAGE);
		_model = model;
	}

	/**
	 * 
	 * 
	 * @param parent
	 * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
	 */
	@Override
	public void createControl(Composite parent) {
		final Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 1;

		final GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		for (ISourceType type : _model.getSourceTypes()) {
			final Button radio = new Button(container, SWT.RADIO);
			radio.setText(type.getName());
			radio.setData("class", type.getClass());
			radio.setLayoutData(gd);
			radio.addSelectionListener(new SelectionListener() {

				@Override
				public void widgetSelected(final SelectionEvent e) {
					if (e.getSource() instanceof Button) {
						final Button b = (Button) e.getSource();
						_sourceTypeClass = (Class<?>) b.getData("class");
						setPageComplete(true);
					}
				}

				@Override
				public void widgetDefaultSelected(SelectionEvent e) {
					// TODO Auto-generated method stub

				}
			});
		}

		// Required to avoid an error in the system
		setControl(container);
		setPageComplete(false);

	}

	/**
	 * 
	 * @return Class<?> the sourceTypeClass
	 */
	protected Class<?> getSourceTypeClass() {
		return _sourceTypeClass;
	}

	/**
	 * 
	 * 
	 * @return SourceType
	 */
	protected ISourceType getSourceType() {
		final Class<?> cl = getSourceTypeClass();
		for (final ISourceType type : _model.getSourceTypes()) {
			if (type.getClass().equals(cl)) {
				return type;
			}
		}
		return null;
	}

}
